import { Cascader, Form, Input, InputNumber, message, Modal } from 'antd';
import React, { useEffect } from 'react';

import { nestedCityCode } from '@/components/CityCode/citycode';
import InputLnglat from '@/components/InputLnglat';
import RemoteSelect from '@/components/RemoteSelect';
import { getSchemeList } from '@/pages/Finance/Scheme/RuleList/service';
import type { ZoneTableListItem, ZoneUpdateItem } from '@/pages/Zones/data';
import { showZoneDetail, updateZone } from '@/pages/Zones/service';
import { SUCCESS_CODE } from '@/utils/request';
import { TimePicker } from 'antd/es';
import moment from 'moment';

interface EditFormProps {
  item: ZoneTableListItem;
  onSubmit: (values: ZoneUpdateItem) => void;
  onCancel: (flag?: boolean) => void;
  modalVisible: boolean;
}

const formItemLayout = {
  labelCol: {
    xs: { span: 6 },
    sm: { span: 6 },
  },
  wrapperCol: {
    xs: { span: 18 },
    sm: { span: 18 },
  },
};

const ZoneEditForm: React.FC<EditFormProps> = (props) => {
  const [form] = Form.useForm();

  useEffect(() => {
    if (!props.item) {
      return;
    }
    showZoneDetail({ id: props.item.id })
      .then((res) => {
        console.debug(res.data);

        form.setFieldsValue({ ...res.data, open_time: undefined });
        const open_time = res.data?.open_time || '00:00-00:00';

        if (open_time) {
          try {
            const startOpenTime: string = open_time.split('-')[0];
            const endOpenTime = open_time.split('-')[1];
            const s = moment(`1970-01-01 ${startOpenTime}:00`);
            const e = moment(`1970-01-01 ${endOpenTime}:00`);
            form.setFieldsValue({
              open_time: [s, e],
            });
          } catch (e) {
            console.log(e);
          }
        }
      })
      .catch((err) => {
        console.log(err);
      });
  }, [props.item.id]);

  const { onSubmit, onCancel: handleAddModalVisible, modalVisible: addModalVisible } = props;

  const onModalOk = async () => {
    const fieldsValue = (await form.validateFields()) as ZoneUpdateItem;

    fieldsValue.id = props.item.id;

    const hide = message.loading('正在修改');
    try {
      const res = await updateZone(fieldsValue);
      hide();
      if (res.code === SUCCESS_CODE) {
        message.success('修改成功');
        onSubmit(fieldsValue);
      } else {
        message.error(`修改失败！${res.message}`);
        handleAddModalVisible(false);
      }
    } catch (error) {
      hide();
      message.error('修改失败！未知的错误！');
      handleAddModalVisible(false);
    }
  };

  form.setFieldsValue(props.item);

  return (
    <Modal
      title="修改停车区域信息"
      visible={addModalVisible}
      destroyOnClose
      onOk={() => onModalOk()}
      onCancel={() => handleAddModalVisible(false)}
      afterClose={() => handleAddModalVisible()}
      okText="确定"
      cancelText="取消"
    >
      <Form {...formItemLayout} form={form}>
        <Form.Item name="name" label="名称" rules={[{ required: true, message: '必选' }]}>
          <Input />
        </Form.Item>
        <Form.Item name="district" label="所在地区">
          <Cascader
            placeholder="选择所在地区"
            fieldNames={{ label: 'name', value: 'code', children: 'children' }}
            options={nestedCityCode}
          />
        </Form.Item>
        <Form.Item name="address" label="地址">
          <Input />
        </Form.Item>

        <Form.Item name="space_total_count" label="总泊位数量">
          <InputNumber min={0} defaultValue={0} />
        </Form.Item>

        <Form.Item name="open_time" label="运营时间" rules={[{ required: true, message: '必选' }]}>
          <TimePicker.RangePicker allowClear format={'HH:mm'} minuteStep={15} />
        </Form.Item>

        <Form.Item name="location" label="所在位置">
          <InputLnglat
            onChange={(values) => {
              form.setFieldsValue({ lat: values.lat, lng: values.lng });
            }}
          />
        </Form.Item>

        <Form.Item name="scheme" label="停车计费规则">
          <RemoteSelect
            style={{ width: '100%' }}
            fieldNames={{ key: 'id', value: 'id', label: 'name' }}
            request={(name) => getSchemeList({ type: 1, name })}
          />
        </Form.Item>
        <Form.Item
          name="reserve_scheme"
          label="预约收费规则"
          rules={[{ required: true, message: '必选' }]}
        >
          <RemoteSelect
            style={{ width: '100%' }}
            fieldNames={{ key: 'id', value: 'id', label: 'name' }}
            request={(name) => getSchemeList({ type: 2, name })}
          />
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default ZoneEditForm;
